package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

//双指针
func reverseList1(head *ListNode) *ListNode {
	if head == nil {
		return nil
	}
	var newHead *ListNode
	//node=head.Next=new=head=node
	for head != nil {
		node := head.Next
		head.Next = newHead
		newHead = head
		head = node
	}
	return newHead
}

//递归
func reverseList2(head *ListNode) *ListNode {
	return help(nil, head)
}

func help(pre, head *ListNode) *ListNode {
	if head == nil {
		return pre
	}
	next := head.Next
	head.Next = pre
	return help(head, next)
}

// AddNode 从末尾添加元素
func AddNode(head *ListNode, data *ListNode) {
	temp := head
	for {
		if temp.Next == nil {
			break
		}
		temp = temp.Next
	}
	temp.Next = data
}

// ShowNode 显示全部链表
func ShowNode(head *ListNode) {
	temp := head
	//判断是否为空
	if temp.Next == nil {
		fmt.Println("error:node is nil")
		return
	}
	//遍历链表
	for {
		fmt.Printf("%v", temp.Val)
		temp = temp.Next
		if temp.Next == nil {
			break
		}
	}
}

func main() {
	//创造头节点
	head := &ListNode{}
	//创造新元素
	n1 := &ListNode{
		Val: 2,
	}
	n2 := &ListNode{
		Val: 4,
	}
	n3 := &ListNode{
		Val: 1,
	}
	n4 := &ListNode{
		Val: 9,
	}
	n5 := &ListNode{
		Val: 9,
	}

	//加入
	AddNode(head, n1)
	AddNode(head, n2)
	AddNode(head, n3)
	AddNode(head, n4)
	AddNode(head, n5)
	// //显示
	// ShowNode(head)
	fmt.Println(reverseList1(n1))
}
